<template>
  <div>
    <!-- <h1>购物车</h1> -->
    <!-- 导航栏 -->
    <van-nav-bar :title="$route.name" @click-left="$router.back()" left-arrow />
    <!-- 购物车分为有数据和无数据两种状态 -->
    <!-- 有数据 -->
    <div v-if="cartlist.length > 0">
      <van-swipe-cell v-for="item in cartlist" :key="item.id">
        <van-card
          :num="item.num"
          :price="(item.price | toPrice)*(item.num)"
          desc="描述信息"
          :title="item.goodsname"
          class="goods-card"
          :thumb="item.img"
        >
          <template #footer>
            <van-stepper
              v-model="item.num"
              theme="round"
              button-size="22"
              disable-input
            />
          </template>
        </van-card>
        <template #right>
          <van-button
            @click="del(item.id)"
            square
            text="删除"
            type="danger"
            class="delete-button btnInfo"
          />
        </template>
      </van-swipe-cell>
    </div>
    <!-- 无数据 -->
    <div v-else>
      <van-empty
        class="custom-image"
        image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
        description="购物车竟然是空的~"
      />
    </div>
  </div>
</template>

<script>
import { cartList,deleteCart } from "../request/api";
import {Toast} from "vant"
export default {
  data() {
    return {
      cartlist: [],
    };
  },
  //进入购物车之前，我们要做权限判断，他只有登录之后，才能进来，否则不让进！！
  //这个时候没有this  会话存储进行判断
  beforeRouteEnter(to, from, next) {
    if (sessionStorage.getItem("userinfo")) {
      next();
    } else {
      //无登录状态，强制跳转到登录页
      next("/login");
    }
  },
  mounted() {
    //组件一加载就调用购物车列表接口
    cartList({
      uid: this.$store.getters.getUser.uid,
      /* 或辅助函数取值 */
    }).then((res) => {
      console.log(res, "购物车列表");
      if (res.code == 200) {
        this.cartlist = res.list?res.list:[];
      }
    });
  },
  methods: {
    //封装一个删除事件
    del(id){
      deleteCart({id})
      .then((res) => {
        if(res.code==200){
          Toast.success(res.msg)
          location.reload()/* 重新加载 */
          // 重新刷新列表接口
        }else{
          Toast.fail(res.msg)
        }
      })
    },
  },
};
</script>

<style scoped>
/* 购物车空  图大小 */
.custom-image .van-empty__image {
  width: 1rem;
  height: 1rem;
}
/* 删除摁钮 */
.btnInfo {
  height: 100%;
}
</style>